#include"Heap.h"


void HPInit(HP* heap)
{
	assert(heap);
	heap->Capacity = 0;
	heap->size = 0;
	heap->data = NULL;
}


void HPDeastroy(HP* heap)
{
	assert(heap);
	free(heap->data);
	heap->data = NULL;
	heap->Capacity = 0;
	heap->size = 0;
}


void Swap(HPDataType* x, HPDataType* y)
{
	HPDataType z;
	z = *x;
	*x = *y;
	*y = z;
}


void AdjustUp(HPDataType* a, int child)
{
	assert(a);
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
			break;
	}
}

void HPPush(HP* heap, HPDataType x)
{
	assert(heap);
	if (heap->size == heap->Capacity)
	{
		int newCap = heap->Capacity == 0 ? 4 : heap->Capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(heap->data, sizeof(HPDataType) * newCap);
		assert(tmp);
		heap->data = tmp;
		heap->Capacity = newCap;
	}
	heap->data[heap->size] = x;
	heap->size++;

	AdjustUp(heap->data, heap->size - 1);
}

void AdjustDown(HPDataType* a, int size, int parent)
{
	assert(a);
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && a[child + 1] < a[child])
			++child;

		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}

void HPPop(HP* heap)
{
	assert(heap);
	assert(heap->size > 0);
	Swap(&heap->data[0], &heap->data[heap->size - 1]);
	heap->size--;
	AdjustDown(heap->data, heap->size, 0);
}

int HPSize(HP* heap)
{
	assert(heap);
	return heap->size;
}

bool HPEmpty(HP* heap)
{
	assert(heap);
	return heap->size == 0;
}

HPDataType HPTop(HP* heap)
{
	assert(heap);
	assert(heap->size > 0);
	return heap->data[0];
}


//
//void AdjustUp(HP* heap)
//{
//	assert(heap);
//	int child = heap->size - 1;
//	int parent = (child - 1) / 2;
//	while(child > 0)
//	{
//		if (heap->data[child] < heap->data[parent])
//		{
//			Swap(&heap->data[child], heap->data[parent]);
//			child = parent;
//			parent = (child - 1) / 2;
//		}
//		else
//			break;
//	}
//}